<!DOCTYPE html>
<html class="client-nojs vector-feature-night-mode-disabled vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-sticky-header-enabled" lang="en" dir="ltr"><head>
<meta charset="UTF-8">
<title>Constant (computer programming)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://en.wikipedia.org/wiki/Constant_(computer_programming)"> <link href="./mw/ext.cite.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/ext.pygments.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.icons.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.search.codex.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/user.styles.css" rel="stylesheet" type="text/css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" type="text/css" href="./mw/site.styles.css">
<link rel="stylesheet" type="text/css" href="./mw/noscript.css">
<link rel="stylesheet" type="text/css" href="./footer.css">
<link rel="stylesheet" type="text/css" href="./vector-2022.css">
</head>
<body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Constant_computer_programming rootpage-Constant_computer_programming skin-vector-2022 action-view">
<div class="mw-page-container">
<div class="mw-page-container-inner">
<div class="mw-content-container">
<main id="content" class="mw-body">
<header class="mw-body-header vector-page-titlebar">
<h1 id="firstHeading" class="firstHeading mw-first-heading">
<span id="openzim-page-title" class="mw-page-title-main"><span class="mw-page-title-main">Constant (computer programming)</span></span>
</h1>
</header>
<a id="top"></a>
<div id="bodyContent" class="vector-body ve-init-mw-desktopArticleTarget-targetContainer" aria-labelledby="firstHeading" data-mw-ve-target-container="">
<div id="mw-content-text" class="mw-body-content mw-content-ltr" lang="en" dir="ltr"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr">
<p>In <a href="Computer_programming" title="Computer programming">computer programming</a>, a <b>constant</b> is a <a href="Value_(computer_science)" title="Value (computer science)">value</a> that is not altered by the <a href="Computer_program" title="Computer program">program</a> during normal <a href="Execution_(computing)" title="Execution (computing)">execution</a>. When associated with an <a href="Identifier_(computer_languages)" title="Identifier (computer languages)">identifier</a>, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. This is contrasted with a <a href="Variable_(computer_science)" title="Variable (computer science)">variable</a>, which is an identifier with a value that can be changed during normal execution. To simplify, constants' values <i>remains,</i> while the values of variables <i>varies,</i> hence both their names.
</p><p>Constants are useful for both programmers and <a href="Compiler" title="Compiler">compilers</a>: for programmers, they are a form of <a href="Self-documenting" class="mw-redirect" title="Self-documenting">self-documenting</a> code and allow reasoning about <a href="Correctness_(computer_science)" title="Correctness (computer science)">correctness</a>, while for compilers, they allow <a href="Compile-time" class="mw-redirect" title="Compile-time">compile-time</a> and <a href="Run_time_(program_lifecycle_phase)" class="mw-redirect" title="Run time (program lifecycle phase)">run-time</a> checks that verify that constancy assumptions are not violated,<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span class="cite-bracket">[</span>a<span class="cite-bracket">]</span></a></sup> and allow or simplify some <a href="Compiler_optimization" class="mw-redirect" title="Compiler optimization">compiler optimizations</a>.
</p><p>There are various specific realizations of the general notion of a constant, with subtle distinctions that are often overlooked. The most significant are: compile-time (statically valued) constants, run-time (dynamically valued) constants, <a href="Immutable_object" title="Immutable object">immutable objects</a>, and constant types (<code><a href="Const" class="mw-redirect" title="Const">const</a></code>).
</p><p>Typical examples of compile-time constants include mathematical constants, values from standards (here <a href="Maximum_transmission_unit" title="Maximum transmission unit">maximum transmission unit</a>), or internal configuration values (here <a href="Characters_per_line" title="Characters per line">characters per line</a>), such as these <a href="C_(programming_language)" title="C (programming language)">C</a> examples:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="k">const</span><span class="w"> </span><span class="kt">float</span><span class="w"> </span><span class="n">PI</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">3.1415927</span><span class="p">;</span><span class="w"> </span><span class="c1">// maximal single float precision</span>
<span class="k">const</span><span class="w"> </span><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">MTU</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1500</span><span class="p">;</span><span class="w"> </span><span class="c1">// Ethernet v2, RFC 894</span>
<span class="k">const</span><span class="w"> </span><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">COLUMNS</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">80</span><span class="p">;</span>
</pre></div>
<p>Typical examples of run-time constants are values calculated based on inputs to a function, such as this <a href="C%2B%2B" title="C++">C++</a> example:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">void</span><span class="w"> </span><span class="nf">f</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="w"> </span><span class="n">s</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">size_t</span><span class="w"> </span><span class="n">l</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">s</span><span class="p">.</span><span class="n">length</span><span class="p">();</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="p">}</span>
</pre></div>
<meta property="mw:PageProp/toc">
<div class="mw-heading mw-heading2"><h2 id="Use">Use</h2></div>
<p>Some <a href="Programming_language" title="Programming language">programming languages</a> make an explicit syntactic distinction between constant and variable symbols, for example considering <a href="Assignment_(computer_science)" title="Assignment (computer science)">assignment</a> to a constant to be a syntax error, while in other languages they are considered syntactically the same (both simply an identifier), and the difference in treatment is semantic (assignment to an identifier is syntactically valid, but if the identifier is a constant it is semantically invalid).
</p><p>A constant value is defined once and can be referenced many times throughout a program. Using a constant instead of specifying the same value multiple times can simplify code maintenance (as in <a href="Don't_repeat_yourself" title="Don't repeat yourself">don't repeat yourself</a>) and can be self documenting by supplying a meaningful name for a value, for instance, <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" style="" dir="ltr">PI</code> instead of 3.1415926.
</p>
<div class="mw-heading mw-heading2"><h2 id="Comparison_with_literals_and_macros">Comparison with literals and macros</h2></div>
<p>There are several main ways to express a data value that doesn't change during program execution that are consistent across a wide variety of programming languages. One very basic way is by simply writing a <a href="Literal_(computer_science)" class="mw-redirect" title="Literal (computer science)">literal</a> number, character, or string into the program code, which is straightforward in C, C++, and similar languages.
</p><p>In assembly language, literal numbers and characters are done using the "immediate mode" instructions available on most microprocessors. The name "immediate" comes from the values being available immediately from the <a href="Instruction_(computer_science)" class="mw-redirect" title="Instruction (computer science)">instruction stream</a>, as opposed to loading them indirectly by looking up a memory address.<sup id="cite_ref-ibmpowerpc_2-0" class="reference"><a href="#cite_note-ibmpowerpc-2"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup> On the other hand, values longer than the microprocessor's word length, such as strings and arrays, are handled indirectly and assemblers generally provide a "data" pseudo-op to embed such data tables in a program.
</p><p>Another way is by defining a symbolic <a href="Macro_(computer_science)" title="Macro (computer science)">macro</a>. Many high-level programming languages, and many assemblers, offer a macro facility where the programmer can define, generally at the beginning of a source file or in a separate definition file, names for different values. A preprocessor then replaces these names with the appropriate values before compiling, resulting in something functionally identical to using literals, with the speed advantages of immediate mode. Because it can be difficult to maintain code where all values are written literally, if a value is used in any repetitive or non-obvious way, it is often named by a macro.
</p><p>A third way is by declaring and defining a variable as being "constant". A <a href="Global_variable" title="Global variable">global variable</a> or <a href="Static_variable" title="Static variable">static variable</a> can be declared (or a symbol defined in assembly) with a keyword qualifier such as <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code>, <code class="mw-highlight mw-highlight-lang-ada mw-content-ltr" style="" dir="ltr"><span class="kr">constant</span></code>, or <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code>, meaning that its value will be set at compile time and should not be changeable at runtime. Compilers generally put static constants in the text section of an object file along with the code itself, as opposed to the data section where non-const initialized data is kept. Some compilers can produce a section specifically dedicated to constants. Memory protection can be applied to this area to prevent overwriting of such constants by errant pointers.
</p><p>These constants differ from literals in a number of ways. Compilers generally place a constant in a single memory location identified by symbol, rather than spread throughout the executable as with a macro. While this precludes the speed advantages of immediate mode, there are advantages in memory efficiency, and debuggers can work with these constants at runtime. Also while macros may be redefined accidentally by conflicting header files in C and C++, conflicting constants are detected at compile time.
</p><p>Depending upon the language, constants can be untyped or typed. In C and C++, macros provide the former, while <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code> provides the latter:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="cp">#define PI 3.1415926535</span>
<span class="k">const</span><span class="w"> </span><span class="kt">float</span><span class="w"> </span><span class="n">pi2</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">3.1415926535</span><span class="p">;</span>
</pre></div>
<p>while in Ada, there are universal numeric types that can be used, if desired:
</p>
<div class="mw-highlight mw-highlight-lang-ada mw-content-ltr" dir="ltr"><pre><span class="no">pi</span> <span class="p">:</span> <span class="kr">constant</span> <span class="p">:=</span> <span class="mf">3.1415926535</span><span class="p">;</span>
<span class="no">pi2</span> <span class="p">:</span> <span class="kr">constant</span> <span class="kt">float</span> <span class="p">:=</span> <span class="mf">3.1415926535</span><span class="p">;</span>
</pre></div>
<p>with the untyped variant being implicitly converted to the appropriate type upon each use.<sup id="cite_ref-3" class="reference"><a href="#cite_note-3"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="Dynamically-valued_constants">Dynamically-valued constants</h2></div>
<p>Besides the <i>static constants</i> described above, many procedural languages such as Ada and C++ extend the concept of constantness toward global variables that are created at initialization time, local variables that are automatically created at runtime on the stack or in registers, to dynamically allocated memory that is accessed by pointer, and to parameter lists in function headers.
</p><p>Dynamically valued constants do not designate a variable as residing in a specific region of memory, nor are the values set at compile time. In C++ code such as
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">float</span><span class="w"> </span><span class="nf">func</span><span class="p">(</span><span class="k">const</span><span class="w"> </span><span class="kt">float</span><span class="w"> </span><span class="n">ANYTHING</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">float</span><span class="w"> </span><span class="n">XYZ</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">someGlobalVariable</span><span class="o">*</span><span class="n">someOtherFunction</span><span class="p">(</span><span class="n">ANYTHING</span><span class="p">);</span>
<span class="w"> </span><span class="p">...</span>
<span class="p">}</span>
</pre></div>
<p>the expression that the constant is initialized to are not themselves constant. Use of constantness is not necessary here for program legality or semantic correctness, but has three advantages:
</p>
<ol><li>It is clear to the reader that the object will not be modified further, once set</li>
<li>Attempts to change the value of the object (by later programmers who do not fully understand the program logic) will be rejected by the compiler</li>
<li>The compiler may be able to perform code optimizations knowing that the value of the object will not change once created.<sup id="cite_ref-dvc_4-0" class="reference"><a href="#cite_note-dvc-4"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup></li></ol>
<p>Dynamically valued constants originated as a language feature with <a href="ALGOL_68" title="ALGOL 68">ALGOL 68</a>.<sup id="cite_ref-dvc_4-1" class="reference"><a href="#cite_note-dvc-4"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup> Studies of Ada and C++ code have shown that dynamically valued constants are used infrequently, typically for 1% or less of objects, when they could be used much more, as some 40–50% of local, non-class objects are actually invariant once created.<sup id="cite_ref-dvc_4-2" class="reference"><a href="#cite_note-dvc-4"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-ada_5-0" class="reference"><a href="#cite_note-ada-5"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup> On the other hand, such "immutable variables" tend to be the default in <a href="Functional_programming" title="Functional programming">functional languages</a> since they favour programming styles with no side-effect (e.g., recursion) or make most declarations immutable by default, such as <a href="ML_(programming_language)" title="ML (programming language)">ML</a>. <a href="Purely_functional_programming" title="Purely functional programming">Purely functional</a> languages even forbid side-effects entirely.
</p><p>Constantness is often used in function declarations, as a promise that when an object is passed by reference, the called function will not change it. Depending on the syntax, either a pointer or the object being pointed to may be constant, however normally the latter is desired. Especially in C++ and C, the discipline of ensuring that the proper data structures are constant throughout the program is called <a href="Const-correctness" class="mw-redirect" title="Const-correctness">const-correctness</a>.
</p>
<div class="mw-heading mw-heading2"><h2 id="Constant_function_parameters">Constant function parameters</h2></div>
<p>In C/C++, it is possible to declare the parameter of a function or method as constant. This is a guarantee that this parameter cannot be inadvertently modified after its initialization by the caller. If the parameter is a pre-defined (built-in) type, it is <a href="Called_by_value" class="mw-redirect" title="Called by value">called by value</a> and cannot be modified. If it is a user-defined type, the variable is the pointer address, which cannot be modified either. However, the content of the object can be modified without limits. Declaring parameters as constants may be a way to signalise that this value <i>should</i> not be changed, but the programmer must keep in mind that checks about modification of an object cannot be done by the compiler.
</p><p>Besides this feature, it is in C++ also possible to declare a function or method as <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code>. This prevents such functions or methods from modifying anything but local variables.
</p><p>In C#, the keyword <code class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><span class="k">const</span></code> exists, but does not have the same effect for function parameters, as it is the case in C/C++. There is, however, a way to "stir" the compiler to do make the check, albeit it is a bit tricky.<sup id="cite_ref-6" class="reference"><a href="#cite_note-6"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="Object-oriented_constants">Object-oriented constants</h2></div>
<p>A constant data structure or object is referred to as "<a href="Immutable_object" title="Immutable object">immutable</a>" in object-oriented parlance. An object being immutable confers some advantages in program design. For instance, it may be "copied" simply by copying its pointer or reference, avoiding a time-consuming copy operation and conserving memory.
</p><p>Object-oriented languages such as C++ extend constantness even further. Individual members of a struct or class may be made const even if the class is not. Conversely, the <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">mutable</span></code> keyword allows a class member to be changed even if an object was instantiated as <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code>.
</p><p>Even functions can be const in C++. The meaning here is that only a const function may be called for an object instantiated as const; a const function doesn't change any non-mutable data.
</p><p>C# has both a <code class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><span class="k">const</span></code> and a <code class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><span class="k">readonly</span></code> qualifier; its const is only for compile-time constants, while <code class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><span class="k">readonly</span></code> can be used in constructors and other runtime applications.
</p>
<div class="mw-heading mw-heading3"><h3 id="Java">Java</h3></div>
<p>Java has a qualifier called <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code> that prevents changing a reference and makes sure it will never point to a different object. This does not prevent changes to the referred object itself. Java's <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code> is basically equivalent to a <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code> <i>pointer</i> in C++. It does not provide the other features of <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code>.
</p><p>In <a href="Java_(programming_language)" title="Java (programming language)">Java</a>, the qualifier <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code> states that the affected data member or variable is not assignable, as below:
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="kd">final</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">3</span><span class="p">;</span>
<span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">4</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error! Cannot modify a "final" object</span>
</pre></div>
<p>It must be decidable by the compilers where the variable with the <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code> marker is initialized, and it must be performed only once, or the class will not compile. Java's <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code> and C++'s <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code> keywords have the same meaning when applied with primitive variables.
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="k">const</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">3</span><span class="p">;</span><span class="w"> </span><span class="c1">// C++ declaration</span>
<span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">4</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error!</span>
</pre></div>
<p>Considering pointers, a <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code> reference in Java means something similar to <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code> pointer in C++. In C++, one can declare a "constant pointer type".
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="n">Foo</span><span class="w"> </span><span class="o">*</span><span class="k">const</span><span class="w"> </span><span class="n">bar</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">mem_location</span><span class="p">;</span><span class="w"> </span><span class="c1">// const pointer type</span>
</pre></div>
<p>Here, <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="n">bar</span></code> must be initialised at the time of declaration and cannot be changed again, but what it points <i>is</i> modifiable. I.e. <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="o">*</span><span class="n">bar</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">value</span></code> is valid. It just can't point to another location. Final references in Java work the same way except that they can be declared uninitialized.
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="kd">final</span><span class="w"> </span><span class="n">Foo</span><span class="w"> </span><span class="n">i</span><span class="p">;</span><span class="w"> </span><span class="c1">// a Java declaration</span>
</pre></div>
<p>Note: Java does not support pointers.<sup id="cite_ref-7" class="reference"><a href="#cite_note-7"><span class="cite-bracket">[</span>6<span class="cite-bracket">]</span></a></sup>
It is because <a href="Pointer_(computer_programming)#Java" title="Pointer (computer programming)">pointers</a> (with restrictions) are the default way of accessing objects in Java, and Java does not use stars to indicate them. For example, <style data-mw-deduplicate="TemplateStyles:r886049734">
/* start https://en.wikipedia.org/ */
.mw-parser-output .monospaced{font-family:monospace,monospace}
/* end https://en.wikipedia.org/ */
</style><span class="monospaced">i</span> in the last example is a pointer and can be used to access the instance.
</p><p>One can also declare a pointer to "read-only" data in C++.
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="k">const</span><span class="w"> </span><span class="n">Foo</span><span class="w"> </span><span class="o">*</span><span class="n">bar</span><span class="p">;</span>
</pre></div>
<p>Here <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" style="" dir="ltr">bar</code> can be modified to point anything, anytime; just that pointed value cannot be modified <i>through</i> <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" style="" dir="ltr">bar</code> pointer.
</p><p>There is no equivalent mechanism in Java. Thus there are also no <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code> methods.
Const-correctness cannot be enforced in Java, although by use of interfaces and defining a read-only interface to the class and passing this around, one can ensure that objects can be passed around the system in a way that they cannot be modified.
</p><p><a href="Java_collections_framework" title="Java collections framework">Java collections framework</a> provides a way to create an immutable wrapper of a <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="n">Collection</span></code> via <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="n">Collections</span><span class="p">.</span><span class="na">unmodifiableCollection</span><span class="p">()</span></code> and similar methods.
</p><p>A method in Java can be declared "final", meaning that it cannot be overridden in subclasses.
</p>
<div class="mw-heading mw-heading3"><h3 id="C#">C#</h3></div>
<p>In <a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a>, the qualifier <code class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><span class="k">readonly</span></code> has the same effect on data members that <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code> does in Java and the <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="k">const</span></code> does in C++; the modifier <code class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><span class="k">const</span></code> has an effect similar (yet typed and class-scoped) to that of <code class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><span class="cp">#define</span></code> in C++. The other, inheritance-inhibiting effect of Java's <code class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><span class="kd">final</span></code> when applied to methods and classes is induced in C# with the aid of the keyword <code class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><span class="k">sealed</span></code>.
</p><p>Unlike C++, C# does not permit methods and parameters to be marked as <code class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><span class="k">const</span></code>. However one may also pass around read-only subclasses, and the <a href=".NET_Framework" title=".NET Framework">.NET Framework</a> provides some support for converting mutable collections to immutable ones which may be passed as read-only wrappers.
</p>
<div class="mw-heading mw-heading2"><h2 id="By_paradigm">By paradigm</h2></div>
<p>Treatment of constants varies significantly by <a href="Programming_paradigm" title="Programming paradigm">programming paradigm</a>. Const-correctness is an issue in imperative languages like C++ because by default <a href="Name_binding" title="Name binding">name bindings</a> typically create <a href="Variable_(computer_science)" title="Variable (computer science)">variables</a>, which can vary, as the name suggests, and thus if one wishes to mark a binding as constant this requires some additional indication.<sup id="cite_ref-8" class="reference"><a href="#cite_note-8"><span class="cite-bracket">[</span>b<span class="cite-bracket">]</span></a></sup> In other programming language paradigms related issues arise, with some analogs to const-correctness found.
</p><p>In <a href="Functional_programming" title="Functional programming">functional programming</a>, data are typically constant by default, rather than variable by default. Instead of assigning a value to a variable (a storage space with a name and potentially variable value), one creates a binding of a name to a value, such as by the <code class="mw-highlight mw-highlight-lang-scheme mw-content-ltr" style="" dir="ltr"><span class="k">let</span></code> construct in many dialects of <a href="Lisp_(programming_language)" title="Lisp (programming language)">Lisp</a>. In some functional languages, particularly multiparadigm ones such as <a href="Common_Lisp" title="Common Lisp">Common Lisp</a>, modifying data is commonplace, while in others it is avoided or considered exceptional; this is the case for <a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a> (another Lisp dialect), which uses the <code class="mw-highlight mw-highlight-lang-scheme mw-content-ltr" style="" dir="ltr"><span class="k">set!</span></code> construct to modify data, with the <span class="monospaced">!</span> exclamation point drawing attention to this. Such languages achieve the goals of const-correctness by default, drawing attention to modification rather than constantness.
</p><p>In a number of <a href="Object-oriented_language" class="mw-redirect" title="Object-oriented language">object-oriented languages</a>, there is the concept of an <a href="Immutable_object" title="Immutable object">immutable object</a>, which is particularly used for basic types like strings; notable examples include Java, JavaScript, Python, and C#. These languages vary in whether user-defined types can be marked as immutable, and may allow particular fields (attributes) of an object or type to be marked as immutable.
</p><p>In some multiparadigm languages that allow both object-oriented and functional styles, both of these features may be combined. For example, in <a href="OCaml" title="OCaml">OCaml</a> object fields are immutable by default and must be explicitly marked with the keyword <code class="mw-highlight mw-highlight-lang-ocaml mw-content-ltr" dir="ltr"><span class="k">mutable</span></code> to be mutable, while in Scala, bindings are explicitly immutable when defined with <code class="mw-highlight mw-highlight-lang-scala mw-content-ltr" style="" dir="ltr"><span class="kd">val</span></code> for "value" and explicitly mutable when defined with <code class="mw-highlight mw-highlight-lang-scala mw-content-ltr" style="" dir="ltr"><span class="kd">var</span></code> for "variable".
</p>
<div class="mw-heading mw-heading2"><h2 id="Naming_conventions">Naming conventions</h2></div>
<p><a href="Naming_conventions_(programming)" class="mw-redirect" title="Naming conventions (programming)">Naming conventions</a> for constants vary. Some simply name them as they would any other variable. Others use capitals and underscores for constants in a way similar to their traditional use for symbolic macros, such as <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" style="" dir="ltr">SOME_CONSTANT</code>.<sup id="cite_ref-9" class="reference"><a href="#cite_note-9"><span class="cite-bracket">[</span>7<span class="cite-bracket">]</span></a></sup> In <a href="Hungarian_notation" title="Hungarian notation">Hungarian notation</a>, a "k" <a href="Prefix" title="Prefix">prefix</a> signifies constants as well as <a href="Macro_(computer_science)" title="Macro (computer science)">macros</a> and <a href="Enumerated_type" title="Enumerated type">enumerated types</a>.
</p><p>One enforced convention is that in <a href="Ruby_(programming_language)" title="Ruby (programming language)">Ruby</a>, any variable that begins with a capital letter is considered a constant, including class names.
</p>
<div class="mw-heading mw-heading2"><h2 id="See_also">See also</h2></div>
<ul><li><a href="Address_constant" title="Address constant">Address constants</a> for the <a href="IBM/360" class="mw-redirect" title="IBM/360">IBM/360</a> and <a href="Z/Architecture" title="Z/Architecture">Z/Architecture</a> platform</li></ul>
<div class="mw-heading mw-heading2"><h2 id="Notes">Notes</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1239543626">
/* start https://en.wikipedia.org/ */
.mw-parser-output .reflist{margin-bottom:0.5em;list-style-type:decimal}@media screen{.mw-parser-output .reflist{font-size:90%}}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}
/* end https://en.wikipedia.org/ */
</style><div class="reflist reflist-lower-alpha">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text">In some cases this can be circumvented, e.g. using <a href="Self-modifying_code" title="Self-modifying code">self-modifying code</a> or by overwriting the <a href="Memory_location" class="mw-redirect" title="Memory location">memory location</a> where the value is stored.</span>
</li>
<li id="cite_note-8"><span class="mw-cite-backlink"><b><a href="#cite_ref-8">^</a></b></span> <span class="reference-text">This is not universal: in Ada input parameters and loop parameters are implicitly constant, for instance.</span>
</li>
</ol></div></div>
<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>
<div class="reflist">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-ibmpowerpc-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-ibmpowerpc_2-0">^</a></b></span> <span class="reference-text">Ex. <a rel="nofollow" class="external text" href="http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.aixassem/doc/alangref/addic.htm">IBM Systems Information</a>. Instruction Set - Assembler Language Reference for PowerPC.</span>
</li>
<li id="cite_note-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-3">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">
/* start https://en.wikipedia.org/ */
.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("./mw/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("./mw/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("./mw/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("./mw/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}
/* end https://en.wikipedia.org/ */
</style><cite id="CITEREFBooch1983" class="citation book cs1"><a href="Grady_Booch" title="Grady Booch">Booch, Grady</a> (1983). <span class="id-lock-registration" title="Free registration required"><a rel="nofollow" class="external text" href="https://archive.org/details/softwareengineer00booc/page/116"><i>Software Engineering with Ada</i></a></span>. <a href="Benjamin_Cummings" title="Benjamin Cummings">Benjamin Cummings</a>. pp. <a rel="nofollow" class="external text" href="https://archive.org/details/softwareengineer00booc/page/116">116–117</a>. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <bdi>0-8053-0600-5</bdi>.</cite></span>
</li>
<li id="cite_note-dvc-4"><span class="mw-cite-backlink">^ <a href="#cite_ref-dvc_4-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-dvc_4-1"><sup><i><b>b</b></i></sup></a> <a href="#cite_ref-dvc_4-2"><sup><i><b>c</b></i></sup></a></span> <span class="reference-text"><cite id="CITEREFSchilling1995" class="citation journal cs1">Schilling, Jonathan L. (April 1995). <a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F202176.202177">"Dynamically-Valued Constants: An Underused Language Feature"</a>. <i><a href="SIGPLAN_Notices" class="mw-redirect" title="SIGPLAN Notices">SIGPLAN Notices</a></i>. <b>30</b> (4): <span class="nowrap">13–</span>20. <a href="Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<span class="id-lock-free" title="Freely accessible"><a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F202176.202177">10.1145/202176.202177</a></span>. <a href="S2CID_(identifier)" class="mw-redirect" title="S2CID (identifier)">S2CID</a> <a rel="nofollow" class="external text" href="https://api.semanticscholar.org/CorpusID:17489672">17489672</a>.</cite></span>
</li>
<li id="cite_note-ada-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-ada_5-0">^</a></b></span> <span class="reference-text"><cite id="CITEREFPerkins" class="citation conference cs1">Perkins, J. A. <i>Programming Practices: Analysis of Ada Source Developed for the Air Force, Army, and Navy</i>. Proceedings TRI-Ada '89. pp. <span class="nowrap">342–</span>354. <a href="Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F74261.74287">10.1145/74261.74287</a>.</cite></span>
</li>
<li id="cite_note-6"><span class="mw-cite-backlink"><b><a href="#cite_ref-6">^</a></b></span> <span class="reference-text">
<cite id="CITEREFTimwi2010" class="citation web cs1">Timwi (2010-09-09). <a rel="nofollow" class="external text" href="https://stackoverflow.com/a/3826657/">"Read-only ("const"-like) function parameters of C#"</a>. Stack Overflow<span class="reference-accessdate">. Retrieved <span class="nowrap">2012-05-06</span></span>. <q>[...] Then you can declare methods whose parameter type "tells" whether it plans on changing the variable or not:. [...] This mimics compile-time checks similar to constness in C++. As Eric Lippert correctly pointed out, this is not the same as immutability. But as a C++ programmer I think you know that.</q></cite></span>
</li>
<li id="cite_note-7"><span class="mw-cite-backlink"><b><a href="#cite_ref-7">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://java.sun.com/docs/white/langenv/Simple.doc2.html#4107">"Oracle Technology Network for Java Developers | Oracle Technology Network | Oracle"</a>. Java.sun.com. 2013-08-14<span class="reference-accessdate">. Retrieved <span class="nowrap">2013-08-18</span></span>.</cite></span>
</li>
<li id="cite_note-9"><span class="mw-cite-backlink"><b><a href="#cite_ref-9">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://msdn.microsoft.com/en-us/library/aa188468(office.10).aspx">Microsoft Office XP Developer: Constant Names</a></span>
</li>
</ol></div></div></div><!--htdig_noindex--><div><div class="zim-footer">
This article is issued from <a class="external text" title="Last edited on 2024-09-24" href="https://en.wikipedia.org/wiki/?title=Constant_(computer_programming)&oldid=1247388994">Wikipedia</a>. The text is available under <a class="external text" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons Attribution-Share Alike 4.0</a> unless otherwise noted. Additional terms may apply for the media files.
</div>
</div><!--/htdig_noindex--></div>
</div>
</main>
</div>
</div>
</div>
</body></html>